package org.platform.processor.task.job;

import com.mc.mic.core.log.bus.BusLogPusher;
import com.mc.mic.core.log.frame.LogBo;
import lombok.extern.slf4j.Slf4j;
import org.platform.constant.LogType;
import org.platform.core.JobManager;
import org.platform.dao.mapper.FdChannelEquMapper;
import org.platform.dao.mapper.FdWorkSchInfoMapper;
import org.platform.mo.bussmo.log.TaskMqBO;
import org.platform.mo.bussmo.task.Fd_ChannelEqu;
import org.platform.mo.bussmo.task.Fd_WorkSchInfo;
import org.platform.mo.db.FdChannelEqu;
import org.platform.mo.db.FdWorkSchInfo;
import org.platform.tool.util.BeansUtils;
import org.quartz.*;
import org.quartz.impl.JobDetailImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 定时推送 测试任务步骤
 *
 * @author FengJie
 * @date 2018/6/19
 */
@Slf4j
@Component
public class PromoteTaskLogJob implements InterruptableJob {
    private static final String JOB_KEY = "PromoteTaskLogJob";
    @Autowired
    private FdWorkSchInfoMapper mapper;
    @Autowired
    private FdChannelEquMapper channelEquMapper;
    @Autowired
    private BusLogPusher mqLog;
    @Autowired
    private JobManager job;

    @Override
    public void interrupt() {

    }

    @Override
    public void execute(JobExecutionContext context) {
        try {
            List<FdWorkSchInfo> fdWorkSchInfoList = mapper.selectAll();
            List<Fd_WorkSchInfo> workSchInfoList = BeansUtils.copyListProperties(fdWorkSchInfoList, Fd_WorkSchInfo.class);
            workSchInfoList.forEach(workSchInfo -> {
                Example example = new Example(FdChannelEqu.class);
                example.createCriteria().andEqualTo("workSchInfoId", workSchInfo.getId());
                List<FdChannelEqu> fdChannelEquList = channelEquMapper.selectByExample(example);
                List<Fd_ChannelEqu> channelEquList = BeansUtils.copyListProperties(fdChannelEquList, Fd_ChannelEqu.class);
                workSchInfo.setChannelEquList(channelEquList);
            });
            mqLog.log(new LogBo<>(LogType.TASK_LOG, new TaskMqBO(workSchInfoList)));
        } catch (Exception e) {
            log.error("定时线程【{}】发生错误,异常信息", JOB_KEY, e);
        }
    }

    /**
     * 初始化当前定时器
     */
    @PostConstruct
    public void init() {
        JobDetailImpl jd = new JobDetailImpl();
        jd.setJobClass(PromoteTaskLogJob.class);
        jd.setKey(JobKey.jobKey(JOB_KEY));

        SimpleTrigger trigger = TriggerBuilder.newTrigger()
                .withSchedule(SimpleScheduleBuilder
                        .simpleSchedule()
                        .withIntervalInSeconds(10)
                        .repeatForever())
                .startNow()
                .build();

        job.register(jd, trigger);
    }
}
